package util

import (
	"fmt"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/service-center-client/constant"
	"math/rand"
	"os/exec"
	"runtime/debug"
	"strconv"
	"strings"
	"time"
)

func GetListenPort() string {
	var cmd *exec.Cmd
	for {
		if p := func() string {
			defer func() {
				if e := recover(); e != nil {
					logger.Errorf("GetListenPort err %s", debug.Stack())
				}
			}()
			defer func() {
				if cmd != nil && cmd.Process != nil {
					err := cmd.Process.Release()
					if err != nil {
						logger.Warnf("get port cmd process fail, err is  %v", err)
					}
				}
			}()
			cmd = exec.Command("netstat", "-ano")
			output, err := cmd.CombinedOutput()
			if err != nil {
				logger.Errorf("exec get port script fail, err is %s", err)
				return ""
			}
			lineAll := strings.Split(string(output), "\n")
			port := strconv.Itoa(rand.Intn(constant.MaxPort-constant.MinPort+1) + constant.MinPort)
			for _, line := range lineAll {
				if strings.Contains(line, fmt.Sprintf(":%s", port)) {
					break
				}
			}
			return port
		}(); p != "" {
			return p
		}
		time.Sleep(1 * time.Second)
	}
}
